package com.management.department.teacherinfosystem.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.management.department.teacherinfosystem.Entity.TheoryStudy;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Repository.TheoryStudyRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;

@RestController
@RequestMapping("/api/theory")
@CrossOrigin(origins = "*")
public class TheoryStudyController {
	@Autowired private TheoryStudyRepository repository;
	@Autowired private UserRepository userRepository;

	@PostMapping
	@Transactional
	public ResponseEntity<?> create(@RequestBody Map<String,Object> payload) {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		TheoryStudy t = new TheoryStudy();
		t.setUserId(current.getId());
		t.setStudyTopic((String) payload.get("study_topic"));
		t.setStudyForm((String) payload.getOrDefault("study_form","集体学习"));
		t.setStudyDate(parseDate(payload.get("study_date")));
		t.setStudyHours(asDouble(payload.get("study_hours")));
		t.setNotes((String) payload.get("notes"));
		repository.save(t);
		return ResponseEntity.ok(Map.of("id", t.getId()));
	}

	@GetMapping("/mine")
	@Transactional(readOnly = true)
	public ResponseEntity<?> mine() {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		return ResponseEntity.ok(repository.findByUserId(current.getId()));
	}

	@PutMapping("/{id}")
	@Transactional
	public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody Map<String,Object> payload) {
		TheoryStudy t = repository.findById(id).orElse(null);
		if (t == null) return ResponseEntity.notFound().build();
		User current = currentUser();
		if (current == null || !Objects.equals(t.getUserId(), current.getId())) return ResponseEntity.status(403).body("无权修改");
		t.setStudyTopic((String) payload.getOrDefault("study_topic", t.getStudyTopic()));
		t.setStudyForm((String) payload.getOrDefault("study_form", t.getStudyForm()));
		Date d = parseDate(payload.get("study_date")); if (d != null) t.setStudyDate(d);
		Double h = asDouble(payload.get("study_hours")); if (h != null) t.setStudyHours(h);
		t.setNotes((String) payload.getOrDefault("notes", t.getNotes()));
        // 教职工修改后回到待审核，清空审核信息
        t.setStatus("PENDING");
        t.setReviewOpinion(null);
        t.setReviewerId(null);
        t.setReviewTime(null);
		repository.save(t);
		return ResponseEntity.ok().build();
	}

	@DeleteMapping("/{id}")
	@Transactional
	public ResponseEntity<?> delete(@PathVariable("id") Long id) {
		TheoryStudy t = repository.findById(id).orElse(null);
		if (t == null) return ResponseEntity.notFound().build();
		User current = currentUser();
		if (current == null || !Objects.equals(t.getUserId(), current.getId())) return ResponseEntity.status(403).body("无权删除");
		repository.deleteById(id);
		return ResponseEntity.ok().build();
	}

    // admin list
    @GetMapping("/all")
    @Transactional(readOnly = true)
    public ResponseEntity<?> all(@RequestParam(value = "startDate", required = false) String startDate,
                                 @RequestParam(value = "endDate", required = false) String endDate,
                                 @RequestParam(value = "status", required = false) String status) {
		User current = currentUser();
		if (current == null) return ResponseEntity.status(401).body("未登录");
		boolean isAdmin = current.getUserRoles().stream().anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
		if (!isAdmin) return ResponseEntity.status(403).body("权限不足");
        if (status != null && !status.isBlank()) {
            return ResponseEntity.ok(repository.findByStatus(status));
        }
        return ResponseEntity.ok(repository.findByDateRange(parseDate(startDate), parseDate(endDate)));
	}

    // 审核（管理员）
    @PostMapping("/{id}/review")
    @Transactional
    public ResponseEntity<?> review(@PathVariable("id") Long id, @RequestBody Map<String,Object> payload) {
        User current = currentUser();
        if (current == null) return ResponseEntity.status(401).body("未登录");
        boolean isAdmin = current.getUserRoles().stream().anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
        if (!isAdmin) return ResponseEntity.status(403).body("权限不足");
        TheoryStudy t = repository.findById(id).orElse(null);
        if (t == null) return ResponseEntity.notFound().build();
        String s = String.valueOf(payload.get("status"));
        if (!"APPROVED".equals(s) && !"REJECTED".equals(s)) return ResponseEntity.badRequest().body("状态无效");
        t.setStatus(s);
        t.setReviewOpinion((String) payload.get("opinion"));
        t.setReviewerId(current.getId());
        t.setReviewTime(new java.util.Date());
        repository.save(t);
        return ResponseEntity.ok().build();
    }

	private Date parseDate(Object value) { if (value==null) return null; try { return new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(value)); } catch(Exception e){ return null; } }
	private Double asDouble(Object v) { return v==null?null:Double.valueOf(String.valueOf(v)); }
	private User currentUser() {
		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth == null ? null : auth.getName();
		return currentUsername == null ? null : userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
	}
} 